package jcn2000;
import java.util.Vector;

public class regressionFunction {

  //the previous values, used to calculate correlation and regression
  private Vector< Float > times;
  private Vector< Float > prices;
  //the function coefficients
  private float a,b, avgX, avgY, correlation;

  public regressionFunction() {
    times = new Vector< Float >();
    prices = new Vector< Float >();
    clear();
  }

  public void clear() {
    times.clear();
    prices.clear();
    a=0;
    b=0;
    avgX=0;
    avgY=0;
    correlation = 0;
  }
  
  public void update(float time, float price) {
    float teller, numerator;
    times.add(time);
    prices.add(price);
    avgX = 0;
    avgY = 0;
    for (int i=0; i<times.size(); i++){
    	avgX += times.elementAt(i);
    	avgY += prices.elementAt(i);
    }
    avgX = avgX / times.size();
    avgY = avgY / prices.size();
    teller = 0;
    numerator = 0;
    for (int i=0; i<times.size(); i++){
    	teller += (times.elementAt(i)-avgX) * (prices.elementAt(i) - avgY);
    	numerator += (times.elementAt(i)-avgX)*(times.elementAt(i)-avgX);
    }
    b= teller / numerator;
    a= avgY - b*avgX;
  }

  public float priceAt(float time){
    return a+time*b;
  }

  //just a helpfunction to print out our model
  public String regressionFunction(){
    return "Value(t) = "+a+" + "+b+"*t";
  }
  
  public int timeWhen(float value){
    //if the price is rising
    if (b>0) {
      if (prices.lastElement() > value)
        //buy after 20 minutes, i.e. never
        return 1000*60*20;
      else
        //buy now
        return 0;
    }
    else {
      //the bestTime is about half a minute(i.e. one voting round) after the price dips below the client preference
      return (int)((value-a)/b)+(1000*30);
    }
  }
  
  //FIXME: add correlation calculations
  public float correlation(){
  	return correlation;
  }
}
